package cn.edu.baiyunu.myapplication.ui.screens.add

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.tween
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.ime
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawing
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
import androidx.compose.material.icons.filled.CalendarToday
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import cn.edu.baiyunu.myapplication.ui.components.GlassmorphismCard
import cn.edu.baiyunu.myapplication.ui.components.GradientBackground
import cn.edu.baiyunu.myapplication.ui.screens.add.components.AmountKeyboard
import cn.edu.baiyunu.myapplication.ui.screens.add.components.CategorySelector
import cn.edu.baiyunu.myapplication.ui.screens.add.components.CustomKeyboard
import cn.edu.baiyunu.myapplication.ui.screens.add.components.DatePickerDialog
import cn.edu.baiyunu.myapplication.ui.screens.add.components.KeyboardItem
import cn.edu.baiyunu.myapplication.ui.screens.add.components.NoteDialog
import cn.edu.baiyunu.myapplication.ui.screens.add.viewmodel.AddEditTransactionViewModel
import cn.edu.baiyunu.myapplication.ui.utils.formatDateTime
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import androidx.compose.foundation.interaction.MutableInteractionSource
import kotlinx.coroutines.delay

/**
 * 添加/编辑交易屏幕
 * 根据原型图重构的版本
 */
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun AddTransactionScreen(
    transactionId: String = "",
    onTransactionAdded: () -> Unit = {},
    onCancel: () -> Unit = {},
    viewModel: AddEditTransactionViewModel = hiltViewModel()
) {
    // 将transactionId传递给ViewModel
    LaunchedEffect(transactionId) {
        if (transactionId.isNotEmpty()) {
            viewModel.loadTransaction(transactionId)
        }
    }
    
    val uiState by viewModel.uiState.collectAsStateWithLifecycle()
    val scrollState = rememberScrollState()
    val focusManager = LocalFocusManager.current
    val keyboardController = LocalSoftwareKeyboardController.current
    
    // 键盘和日期选择器显示状态
    var showCustomKeyboard by remember { mutableStateOf(false) }
    var showDatePicker by remember { mutableStateOf(false) }
    var showNoteDialog by remember { mutableStateOf(false) }
    
    // 交易类型选择
    val isExpense = uiState.transactionType == "expense"
    
    // 监控保存状态
    LaunchedEffect(uiState.isSaved) {
        if (uiState.isSaved) {
            onTransactionAdded()
        }
    }
    
    // 日期选择器
    if (showDatePicker) {
        DatePickerDialog(
            currentDateMillis = uiState.selectedDate,
            onDateSelected = { 
                viewModel.setDate(it)
                showDatePicker = false
            },
            onDismiss = { 
                showDatePicker = false
            }
        )
    }
    
    // 备注输入对话框
    if (showNoteDialog) {
        NoteDialog(
            initialNote = uiState.note,
            onNoteChange = { viewModel.setNote(it) },
            onDismiss = { showNoteDialog = false }
        )
    }
    
    Box(modifier = Modifier.fillMaxSize()) {
        // 渐变背景
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(
                    brush = Brush.linearGradient(
                        colors = listOf(
                            Color(0xFF6A11CB),
                            Color(0xFF2575FC)
                        )
                    )
                )
        )
        
        // 主要内容
        Column(
            modifier = Modifier
                .fillMaxSize()
                .statusBarsPadding()
                .imePadding() // 添加IME padding以适应系统键盘
                .let {
                    if (showCustomKeyboard) {
                        it.clickable(
                            interactionSource = remember { MutableInteractionSource() },
                            indication = null
                        ) {
                            showCustomKeyboard = false
                        }
                    } else {
                        it
                    }
                }
                .verticalScroll(scrollState)
                .padding(horizontal = 20.dp)
        ) {
            // 顶部栏
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = 20.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                // 关闭按钮
                Box(
                    modifier = Modifier
                        .size(40.dp)
                        .clip(CircleShape)
                        .background(Color.White.copy(alpha = 0.1f))
                        .clickable {
                            // 关闭前隐藏键盘
                            keyboardController?.hide()
                            onCancel()
                        },
                    contentAlignment = Alignment.Center
                ) {
                    Icon(
                        imageVector = Icons.Default.Close,
                        contentDescription = "关闭",
                        tint = Color.White
                    )
                }
                
                // 标题
                Text(
                    text = if (uiState.isEditMode) "编辑交易" else "添加新交易",
                    color = Color.White,
                    fontSize = 20.sp,
                    fontWeight = FontWeight.Medium,
                    modifier = Modifier
                        .weight(1f)
                        .padding(horizontal = 16.dp),
                    textAlign = TextAlign.Center
                )
                
                // 保存按钮
                Box(
                    modifier = Modifier
                        .clip(RoundedCornerShape(20.dp))
                        .background(
                            if (uiState.isLoading) Color.Gray.copy(alpha = 0.3f)
                            else Color(0xFF26DE81).copy(alpha = 0.2f)
                        )
                        .clickable(enabled = !uiState.isLoading) { 
                            // 保存前隐藏键盘
                            keyboardController?.hide()
                            focusManager.clearFocus()
                            viewModel.saveTransaction() 
                        }
                        .padding(horizontal = 15.dp, vertical = 8.dp),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = "保存",
                        color = Color.White,
                        fontSize = 14.sp
                    )
                }
            }
            
            // 交易类型切换
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 25.dp)
            ) {
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(50.dp)
                        .clip(RoundedCornerShape(20.dp))
                        .background(Color.White.copy(alpha = 0.1f))
                        .padding(2.dp)
                ) {
                    // 支出选项
                    Box(
                        modifier = Modifier
                            .weight(1f)
                            .fillMaxSize()
                            .clip(RoundedCornerShape(18.dp))
                            .background(
                                if (isExpense) Color.White.copy(alpha = 0.2f)
                                else Color.Transparent
                            )
                            .clickable { 
                                // 点击类型切换时取消焦点
                                focusManager.clearFocus()
                                viewModel.setTransactionType("expense") 
                            },
                        contentAlignment = Alignment.Center
                    ) {
                        Text(
                            text = "支出",
                            color = if (isExpense) Color(0xFFFF5E62) else Color.White.copy(alpha = 0.7f),
                            fontWeight = if (isExpense) FontWeight.Bold else FontWeight.Normal,
                            fontSize = 16.sp
                        )
                    }
                    
                    // 收入选项
                    Box(
                        modifier = Modifier
                            .weight(1f)
                            .fillMaxSize()
                            .clip(RoundedCornerShape(18.dp))
                            .background(
                                if (!isExpense) Color.White.copy(alpha = 0.2f)
                                else Color.Transparent
                            )
                            .clickable { 
                                // 点击类型切换时取消焦点
                                focusManager.clearFocus() 
                                viewModel.setTransactionType("income") 
                            },
                        contentAlignment = Alignment.Center
                    ) {
                        Text(
                            text = "收入",
                            color = if (!isExpense) Color(0xFF26DE81) else Color.White.copy(alpha = 0.7f),
                            fontWeight = if (!isExpense) FontWeight.Bold else FontWeight.Normal,
                            fontSize = 16.sp
                        )
                    }
                }
            }
            
            // 表单卡片 - 使用毛玻璃效果
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .clip(RoundedCornerShape(24.dp))
                    .background(Color.White.copy(alpha = 0.1f))
                    .padding(25.dp)
            ) {
                Column(
                    modifier = Modifier.fillMaxWidth(),
                    verticalArrangement = Arrangement.spacedBy(20.dp)
                ) {
                    // 金额输入区域
                    Column(modifier = Modifier.fillMaxWidth()) {
                        Text(
                            text = "金额",
                            color = Color.White.copy(alpha = 0.8f),
                            fontSize = 14.sp,
                            modifier = Modifier.padding(bottom = 10.dp)
                        )
                        
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .clip(RoundedCornerShape(12.dp))
                                .background(Color.White.copy(alpha = 0.07f))
                                .clickable { 
                                    focusManager.clearFocus() // 清除其他元素的焦点
                                    showCustomKeyboard = true
                                }
                                .padding(vertical = 15.dp, horizontal = 15.dp)
                        ) {
                            Row(
                                verticalAlignment = Alignment.CenterVertically,
                                modifier = Modifier.fillMaxWidth()
                            ) {
                                Text(
                                    text = if (uiState.amount.isEmpty()) "0.00" else uiState.amount,
                                    color = Color.White,
                                    fontSize = 24.sp,
                                    fontWeight = FontWeight.Bold,
                                    textAlign = TextAlign.Center,
                                    modifier = Modifier.fillMaxWidth()
                                )
                            }
                        }
                        
                        // 错误提示
                        if (uiState.amountError) {
                            Text(
                                text = "请输入金额",
                                color = Color(0xFFFF5E62),
                                fontSize = 12.sp,
                                modifier = Modifier.padding(top = 5.dp)
                            )
                        }
                    }
                    
                    // 分类选择
                    Column(modifier = Modifier.fillMaxWidth()) {
                        Text(
                            text = "分类",
                            color = Color.White.copy(alpha = 0.8f),
                            fontSize = 14.sp,
                            modifier = Modifier.padding(bottom = 10.dp)
                        )
                        
                        // 显示分类网格
                        CategorySelector(
                            categories = if (isExpense) uiState.expenseCategories else uiState.incomeCategories,
                            selectedCategoryId = uiState.categoryId,
                            onCategorySelected = { 
                                focusManager.clearFocus() // 点击分类时清除焦点
                                viewModel.setCategory(it) 
                            }
                        )
                        
                        // 错误提示
                        if (uiState.categoryError) {
                            Text(
                                text = "请选择分类",
                                color = Color(0xFFFF5E62),
                                fontSize = 12.sp,
                                modifier = Modifier.padding(top = 5.dp)
                            )
                        }
                    }
                    
                    // 日期选择
                    Column(modifier = Modifier.fillMaxWidth()) {
                        Text(
                            text = "日期",
                            color = Color.White.copy(alpha = 0.8f),
                            fontSize = 14.sp,
                            modifier = Modifier.padding(bottom = 10.dp)
                        )
                        
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .clip(RoundedCornerShape(12.dp))
                                .background(Color.White.copy(alpha = 0.07f))
                                .clickable { 
                                    focusManager.clearFocus() // 清除其他元素的焦点
                                    showDatePicker = true 
                                }
                                .padding(vertical = 15.dp, horizontal = 15.dp)
                        ) {
                            Row(
                                verticalAlignment = Alignment.CenterVertically,
                                modifier = Modifier.fillMaxWidth()
                            ) {
                                Text(
                                    text = formatDateTime(uiState.selectedDate),
                                    color = Color.White,
                                    modifier = Modifier.weight(1f)
                                )
                                
                                Icon(
                                    imageVector = Icons.Default.CalendarToday,
                                    contentDescription = "选择日期",
                                    tint = Color.White.copy(alpha = 0.7f)
                                )
                            }
                        }
                    }
                    
                    // 备注选择区域（改为点击打开对话框）
                    Column(modifier = Modifier.fillMaxWidth()) {
                        Text(
                            text = "备注",
                            color = Color.White.copy(alpha = 0.8f),
                            fontSize = 14.sp,
                            modifier = Modifier.padding(bottom = 10.dp)
                        )
                        
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .clip(RoundedCornerShape(12.dp))
                                .background(Color.White.copy(alpha = 0.07f))
                                .clickable { showNoteDialog = true }
                                .padding(vertical = 15.dp, horizontal = 15.dp)
                        ) {
                            Row(
                                verticalAlignment = Alignment.CenterVertically,
                                modifier = Modifier.fillMaxWidth()
                            ) {
                                Text(
                                    text = if (uiState.note.isEmpty()) "添加备注..." else uiState.note,
                                    color = if (uiState.note.isEmpty()) Color.White.copy(alpha = 0.5f) else Color.White,
                                    modifier = Modifier.weight(1f)
                                )
                                
                                Icon(
                                    imageVector = Icons.Default.Edit,
                                    contentDescription = "编辑备注",
                                    tint = Color.White.copy(alpha = 0.7f)
                                )
                            }
                        }
                    }
                }
            }
            
            // 底部间距，确保内容不被键盘遮挡
            Spacer(modifier = Modifier.height(if (showCustomKeyboard) 260.dp else 50.dp))
        }
        
        // 自定义键盘
        AnimatedVisibility(
            visible = showCustomKeyboard,
            enter = slideInVertically(
                initialOffsetY = { it },
                animationSpec = tween(durationMillis = 300)
            ),
            exit = slideOutVertically(
                targetOffsetY = { it },
                animationSpec = tween(durationMillis = 300)
            ),
            modifier = Modifier
                .align(Alignment.BottomCenter)
        ) {
            CustomKeyboard(
                onNumberClick = { digit ->
                    // 如果是小数点，且当前已有小数点，则不做任何操作
                    if (digit == "." && uiState.amount.contains(".")) return@CustomKeyboard
                    
                    // 如果已有两位小数，且不是添加小数点，则不做任何操作
                    if (uiState.amount.contains(".")) {
                        val decimalPart = uiState.amount.split(".")[1]
                        if (decimalPart.length >= 2 && digit != ".") return@CustomKeyboard
                    }
                    
                    // 如果当前为空且输入小数点，自动补0
                    val newAmount = when {
                        uiState.amount.isEmpty() && digit == "." -> "0."
                        uiState.amount == "0" && digit != "." -> digit
                        else -> uiState.amount + digit
                    }
                    
                    viewModel.setAmount(newAmount)
                },
                onDeleteClick = {
                    if (uiState.amount.isNotEmpty()) {
                        viewModel.setAmount(uiState.amount.dropLast(1))
                    }
                }
            )
        }
    }
} 